package com.blogsoho.taurus.services.impl;

import com.blogsoho.taurus.cache.LocalCache;
import com.blogsoho.taurus.dao.mapper.CategoryMapper;
import com.blogsoho.taurus.services.CategoryService;
import com.blogsoho.taurus.vm.CategoryViewModel;
import com.blogsoho.taurus.vo.CategoryCountVO;
import com.blogsoho.taurus.vo.ContentVO;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by user on 2017/6/6.
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryViewModel> getAllCategory() throws Exception {
        List<CategoryViewModel> categories = new ArrayList<>();
        Map<String, CategoryCountVO> group = categoryMapper.getCountByCategory();
        List<ContentVO> contents = categoryMapper.getAllCategory();
        if (contents != null && contents.size() > 0) {
            for (ContentVO content : contents) {
                CategoryViewModel model = new CategoryViewModel();
                BeanUtils.copyProperties(model, content);
                if (group.containsKey(content.getObjectId())) {
                    model.setTotal(group.get(content.getObjectId()).getTotal());
                } else {
                    model.setTotal(0);
                }
                categories.add(model);
            }
        }
        return categories;

    }

    @Override
    public String getCategoryName(int id) throws Exception {
        String name = LocalCache.getCategoryName(id);
        if (StringUtils.isEmpty(name)) {
            List<ContentVO> contents = categoryMapper.getAllCategory();
            ConcurrentHashMap<Integer, String> categoryCacheMap = new ConcurrentHashMap<>();
            for (ContentVO content : contents) {
                categoryCacheMap.put(content.getId(), content.getTitle());
            }
            LocalCache.setCategoryCacheMap(categoryCacheMap);
            name = LocalCache.getCategoryName(id);
        }
        return name;
    }
}
